<?php

namespace App\Services;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\Json;
use App\Consts\DingTalkConst;
use App\Consts\GlobalConst;
use App\Consts\MemcacheConst;
use App\Consts\MessageConst;
use App\Consts\SmsConst;

/**
 * 消息发送记录服务
 * Class MsgSendService
 * @package App\Services
 */
class MsgSendService extends BaseService
{

    /**
     * MsgSendService constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->repository = repository()->MsgSendRepository;
    }

    /**
     * 获取搜索列表
     * @param $params
     * @return array
     */
    public function getSearchData($params)
    {
        // 获取默认值
        $params['start_time'] = !empty($params['start_time']) ? strtotime($params['start_time']) : time() - GlobalConst::DEFAULT_QUERY_TIME;
        $params['end_time'] = !empty($params['end_time']) ? strtotime($params['end_time']) : time();
        $params['limit'] = !empty($params['limit']) ? $params['limit'] : GlobalConst::BASE_PAGE_COUNT;
        $params['offset'] = !empty($params['offset']) ? $params['offset'] : GlobalConst::DEFAULT_OFFSET;
        $params['page'] = !empty($params['page']) ? $params['page'] : GlobalConst::DEFAULT_PAGE;
        $params['order_type'] = !empty($params['order']) ? $params['order'] : GlobalConst::DEFAULT_ORDER_TYPE;
        $params['order_field'] = !empty($params['sort']) ? $params['sort'] : GlobalConst::DEFAULT_ORDER_FIELD;

        // 获取查询列表
        $list = $this->repository->getSearchListByCondition($params);
        foreach ($list['rows'] as &$val) {
            $val['scene'] = $this->MsgSceneService->getSceneName($val['scene_id']);
            $val['role'] = MemcacheConst::OPTIONS_ROLE_LIST[$val['role']];
            $val['city'] = MemcacheConst::OPTIONS_CITY_LIST[$val['city']];
            $val['campus'] = MemcacheConst::OPTIONS_CAMPUS_LIST[$val['campus']];
            $val['status'] = MessageConst::TASK_STATUS_LIST[$val['status']]['name'];
            $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
            $val['body'] = $body = Json::decode($val['body']);
            if ($val['channel_id'] === MessageConst::CHANNEL_DINGTALK_ID) {
                $val['channel'] = MessageConst::CHANNEL_DINGTALK_SN;
                $val['body'] = !empty($body['msg']) ? Json::encode(Json::decode($body['msg'])) : Json::encode($body);
                $typeList = DingTalkConst::DINGTALK_TEMPLATE_LIST;
                if ($val['msg_type'] == MessageConst::CHANNEL_OTHER_ID) {
                    $val['msg_type'] = MessageConst::CHANNEL_OTHER_SN;
                } else {
                    $val['msg_type'] = isset($typeList[$val['msg_type']]['name']) ? DingTalkConst::DINGTALK_TEMPLATE_LIST[$val['msg_type']]['name'] : MessageConst::CHANNEL_OTHER_SN;
                }
            } elseif ($val['channel_id'] === MessageConst::CHANNEL_SMS_ID) {
                $val['body'] = $body = Json::encode($val['body']);
                $val['channel'] = MessageConst::CHANNEL_SMS_SN;
                $typeList = SmsConst::SMS_TEMPLATE_LIST;
                if ($val['msg_type'] == MessageConst::CHANNEL_OTHER_ID) {
                    $val['msg_type'] = MessageConst::CHANNEL_OTHER_SN;
                } else {
                    $val['msg_type'] = !empty($typeList[$val['template']]['name']) ? SmsConst::SMS_TEMPLATE_LIST[$val['template']]['name'] : MessageConst::CHANNEL_OTHER_SN;
                }
            } elseif ($val['channel_id'] == MessageConst::CHANNEL_OTHER_ID) {
                $val['channel'] = MessageConst::CHANNEL_OTHER_SN;
                $val['msg_type'] = MessageConst::CHANNEL_OTHER_SN;
            }
            // 填充默认值
            $val['body'] = $val['body'] ? : ' - ';
            $val['result'] = $val['result'] ? : ' - ';
            $val['remark'] = $val['remark'] ? : ' - ';
        }

        return $list;
    }

    /**
     * 获取渠道统计数据
     * @param $params
     * @return mixed
     */
    public function getStatisticData($params)
    {
        $channelId = !empty($params['channel_id']) ? $params['channel_id'] : 0;
        if (empty($params['start_time']) || empty($params['end_time'])) {
            // 默认查询最近 30 天的统计数据
            $params['time_ary'] = [time() - GlobalConst::DEFAULT_QUERY_TIME, time()];
        } else {
            $params['time_ary'] = [strtotime($params['start_time']), strtotime($params['end_time'])];
        }
        // 返回查询结果
        return $this->getChannelData($channelId, $params);
    }

    /**
     * 获取全渠道类型
     * @param $channelId
     * @param $params
     * @return array
     */
    protected function getChannelData($channelId, $params)
    {
        // 获取类型列表
        $dingType = $smsType = [];
        $smsTypeList = $dingTypeList = $firstTypeList = [];
        if (!$channelId || MessageConst::CHANNEL_DINGTALK_ID == $channelId) {
            $dingType = array_values(DingTalkConst::DINGTALK_TEMPLATE_LIST);
            $dingTypeList = ArrayHelper::getColumn($dingType, 'name');
        }
        if (!$channelId || MessageConst::CHANNEL_SMS_ID == $channelId) {
            $smsType = array_values(SmsConst::SMS_TEMPLATE_LIST);
            $smsTypeList = ArrayHelper::getColumn($smsType, 'name');
        }
        if (!$channelId) {
            $firstTypeList = [
                MessageConst::CHANNEL_SMS_NAME,
                MessageConst::CHANNEL_DINGTALK_NAME,
                MessageConst::CHANNEL_OTHER_NAME
            ];
        }
        $typeList = ArrayHelper::merge($firstTypeList, $dingTypeList, $smsTypeList);

        // 查询统计数据
        $rows = [];
        $total = 0;
        $firstType = [];

        if (!$channelId || MessageConst::CHANNEL_DINGTALK_ID == $channelId) {
            foreach ($dingType as $type) {
                $count = $this->repository->getCountByChannelIdAndTime(MessageConst::CHANNEL_DINGTALK_ID, $params['time_ary'], $type['msg_type']);
                $count += MessageConst::STAT_BASE_COUNT;
                $rows[] = ['name' => $type['name'], 'value' => $count];
                $total += $count;
            }
            $firstType[] = ['name' => MessageConst::CHANNEL_DINGTALK_NAME, 'value' => $total, 'selected' => true];
            $total = 0;
        }

        if (!$channelId || MessageConst::CHANNEL_SMS_ID == $channelId) {
            foreach ($smsType as $type) {
                $count = $this->repository->getCountByChannelIdAndTime(MessageConst::CHANNEL_SMS_ID, $params['time_ary'], null, $type['template']);
                $count += MessageConst::STAT_BASE_COUNT;
                $rows[] = ['name' => $type['name'], 'value' => $count];
                $total += $count;
            }
            $firstType[] = ['name' => MessageConst::CHANNEL_SMS_NAME, 'value' => $total];
        }

        if (!$channelId) {
            // other
            $firstType[] = ['name' => MessageConst::CHANNEL_OTHER_NAME, 'value' => 0];
            $rows[] = ['name' => MessageConst::CHANNEL_OTHER_NAME, 'value' => 0];
        }

        // 返回查询结果
        return [
            'first_type' => $firstType,
            'all_type' => $typeList,
            'rows' => $rows,
        ];
    }

    /**
     * 获取类型列表
     * @param string $type
     * @return array
     */
    public function getTypeList($type = '')
    {
        $typeList = [];
        if ($type) {
            switch ($type) {
                case 'platform' :
                    $typeList['platform'] = $this->MsgPlatformService->getPlatformList();
                    break;
                case 'channel' :
                    $typeList['channel'] = $this->MsgChannelService->getChannelList();
                    break;
                case 'scene' :
                    $typeList['scene'] = $this->MsgSceneService->getSceneList();
                    break;
                case 'status' :
                    $typeList['status'] = MessageConst::TASK_STATUS_LIST;
                    break;
                default :
                    break;
            }
            return $typeList;
        }
        $typeList['platform'] = $this->MsgPlatformService->getPlatformList();
        $typeList['channel'] = $this->MsgChannelService->getChannelList();
        $typeList['scene'] = $this->MsgSceneService->getSceneList();
        $typeList['status'] = MessageConst::TASK_STATUS_LIST;
        return $typeList;
    }

    /**
     * 获取详情
     * @param $taskId
     * @return array|string
     */
    public function getDetail($taskId)
    {
        return $this->repository->getInfoByTaskId($taskId);
    }

    /**
     * 获取推送状态
     * @param $taskId
     * @return int|mixed
     */
    public function getTaskStatus($taskId)
    {
        $status = $this->repository->getStatusByTaskId($taskId);
        if (is_null($status)) {
            return $this->throwError(lang('No such a task'));
        }
        return ['send_status' => $status];
    }

    /**
     * 获取验证码
     * @param $taskId
     * @param $mobile
     * @return mixed|string
     */
    public function getCode($taskId, $mobile)
    {
        return $this->repository->getCodeByTaskIdAndMobile($taskId, $mobile);
    }

    /**
     * 添加推送数据
     * @param $data
     * @return mixed
     */
    public function addMsgData($data)
    {
        if (date('d') >= 20) {
            $this->repository->cloneTable();
        }
        return $this->repository->add($data);
    }

    /**
     * 更新推送状态
     * @param $taskId
     * @param $status
     * @param string $remark
     * @return int
     */
    public function updateStatus($taskId, $status, $remark = '')
    {
        return $this->repository->updateStatusByTaskId($taskId, $status, $remark);
    }

    /**
     * 更新推送信息
     * @param $messageId
     * @param $push
     * @param string $remark
     * @return int
     */
    public function updatePushInfo($messageId, $push, $remark = '')
    {
        if ($remark) {
            $info = $this->repository->getInfoById($messageId);
            $remark = !empty($info['remark']) ? $info['remark'] . ' --> ' . $remark : $remark;
        }
        return $this->repository->updatePushInfoById($messageId, $push, $remark);
    }

}